from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from ..models import ChatRoom, ChatMessage, User
from ..utils.logger import get_logger

logger = get_logger(__name__)


class ChatService:
    """聊天服务类"""
    
    @staticmethod
    def create_chat_room(db: Session, name: str, description: Optional[str], creator: User) -> ChatRoom:
        """创建新的聊天室"""
        # 创建聊天室
        chat_room = ChatRoom(
            name=name,
            description=description
        )
        
        # 添加创建者为成员
        chat_room.members.append(creator)
        
        db.add(chat_room)
        db.commit()
        db.refresh(chat_room)
        
        logger.info(f"Chat room created: {name} by user {creator.username}")
        return chat_room
    
    @staticmethod
    def add_member_to_room(db: Session, chat_room_id: int, user: User) -> bool:
        """添加用户到聊天室"""
        chat_room = db.query(ChatRoom).filter(ChatRoom.id == chat_room_id).first()
        if not chat_room:
            return False
        
        # 检查用户是否已经是成员
        if user in chat_room.members:
            return True
        
        # 添加用户到聊天室
        chat_room.members.append(user)
        db.commit()
        
        logger.info(f"User {user.username} added to chat room {chat_room.name}")
        return True
    
    @staticmethod
    def send_message(db: Session, content: str, chat_room_id: int, sender_type: str = "user") -> ChatMessage:
        """发送消息到聊天室"""
        # 创建消息
        message = ChatMessage(
            content=content,
            sender_type=sender_type,
            chat_room_id=chat_room_id
        )
        
        db.add(message)
        db.commit()
        db.refresh(message)
        
        logger.info(f"Message sent to room {chat_room_id} by {sender_type}")
        return message
    
    @staticmethod
    def get_room_messages(db: Session, chat_room_id: int, skip: int = 0, limit: int = 100) -> List[ChatMessage]:
        """获取聊天室的消息历史"""
        messages = db.query(ChatMessage).filter(
            ChatMessage.chat_room_id == chat_room_id
        ).order_by(ChatMessage.created_at.asc()).offset(skip).limit(limit).all()
        
        return messages
    
    @staticmethod
    def get_user_rooms(db: Session, user: User) -> List[ChatRoom]:
        """获取用户加入的所有聊天室"""
        return user.chat_rooms